package com.ssm.wzl.test;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 2017/5/18 0018.
 */
public class SimpleCGLibDemo {

    static class RelaService{
       public void sayHello(){
            System.out.println("Hello");
       }
    }


    static class SimpleInterceptor implements MethodInterceptor{

        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("entering"+method.getName());
            Object result = methodProxy.invokeSuper(o, objects);
            System.out.println("leaving"+method.getName());

            return result;
        }
    }

    @SuppressWarnings("unchecked")
    private static <T>T getProxy (Class<T> c){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(c);
        enhancer.setCallback(new SimpleInterceptor());

        return (T)enhancer.create();

    }


    public static void main(String [] org){
        RelaService service = getProxy(RelaService.class);
        service.sayHello();
    }


}
